package data.join.com.utils;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by Administrator on 2017/9/19.
 */

public class UDPBroadCast {
    public static void sendBroadCastToCenter(Context context){
        WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();

        /*这里获取了IP地址，获取到的IP地址还是int类型的。*/
        final int ip = wifiInfo.getIpAddress();


        /*这里就是将int类型的IP地址通过工具转化成String类型的，便于阅读
        String ips = Formatter.formatIpAddress(ip);
        */

        new Thread(){
            @Override
            public void run() {
                        /*这一步就是将本机的IP地址转换成xxx.xxx.xxx.255*/
                int mPort = 8091;
                int broadCastIP = ip | 0xFF000000;
                String serverIp = Formatter.formatIpAddress(broadCastIP);
                MyLog.D("address UDP serverIp="+serverIp);
                try {
                    InetAddress server = InetAddress.getByName(serverIp);

                    DatagramSocket theSocket = new DatagramSocket();

                    String data = "Hello";

                    DatagramPacket theOutput = new DatagramPacket(data.getBytes(), data.length(), server, mPort);
                /*这一句就是发送广播了，其实255就代表所有的该网段的IP地址，是由路由器完成的工作*/

                    theSocket.send(theOutput);

                    byte[] buffer = new byte[1024];
                    DatagramPacket receivePacket = new DatagramPacket(buffer,buffer.length);

                    theSocket.receive(receivePacket);

                    String s = new String(receivePacket.getData(), 0, receivePacket.getLength(), "UTF-8");
                    MyLog.D("address : " + receivePacket.getAddress() + ", port : " + receivePacket.getPort() + ", content : " + s);

                    theSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }
}
